package test.abcode.image.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import test.abcode.image.service.ImageTranslationService;
import test.abcode.image.service.TranslatorService;

import java.io.IOException;

@Controller
@RequestMapping("/image")
public class ImageTranslationController {

    private final ImageTranslationService imageTranslationService;
    private final TranslatorService translatorService;

    @Value("${image.output-path}")
    private String outputImagePath;

    public ImageTranslationController(ImageTranslationService imageTranslationService, TranslatorService translatorService) {
        this.imageTranslationService = imageTranslationService;
        this.translatorService = translatorService;
    }

    // 显示图片上传和翻译页面
    @GetMapping("/translate")
    public String showTranslatePage() {
        return "image-translate";
    }

    // 处理图片上传及翻译
    @PostMapping("/translate")
    public String translateImage(
            @RequestParam("image") MultipartFile imageFile,    // 图片文件上传
            @RequestParam("language") String targetLanguage,   // 目标语言
            Model model // 将响应结果传递给页面
    ) {
        try {
            // 上传的图片名
            String imageName = imageFile.getOriginalFilename();
            // 保存图片到本地
            String inputImagePath = saveUploadedFile(imageFile);

            // 处理图像并翻译文字
            imageTranslationService.processImage(inputImagePath, targetLanguage, imageName);

            model.addAttribute("message", "Image processed and translated successfully!");
            return "image-translate"; // 返回 Thymeleaf 页面
        } catch (Exception e) {
            model.addAttribute("message", "Error processing image: " + e.getMessage());
            return "image-translate"; // 返回错误消息
        }
    }

    private String saveUploadedFile(MultipartFile imageFile) throws IOException {
        // 保存上传的文件到本地（也可以选择保存到其他位置）
        String inputImagePath = "E:\\free\\upload-img\\" + imageFile.getOriginalFilename();
        imageFile.transferTo(new java.io.File(inputImagePath));
        return inputImagePath;
    }
}
